package com.demo.common.file;

import com.demo.common.exceptions.ServiceException;
import lombok.SneakyThrows;
import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * 本地文件系统
 */
@Component
@ConditionalOnExpression("#{'local'.equals(environment['moudle-type.file'])}")
public class LocalFileSystem implements FileOperator {

    /**
     * 本地文件存储路径
     */
    private final String FILE_ROOT = "E:/fileRoot";


    @Override
    @SneakyThrows
    public String upload(MultipartFile file) {
        Assert.notNull(file, "保存文件不能为空");
        String newFileName = FileUtils.getNewFileName(file.getOriginalFilename());
        Path path = Paths.get(FILE_ROOT);
        if (!Files.exists(path)) {
            Files.createDirectories(path);
        }
        Files.copy(file.getInputStream(),path.resolve(newFileName));
        return newFileName;
    }

    @Override
    @SneakyThrows
    public void downLoad(String fileName, HttpServletResponse response) {
        Assert.notNull(fileName, "文件名不能为空");
        File file = new File(FILE_ROOT, fileName);
        if (!file.exists()) {
            throw new ServiceException("文件" + fileName + "不存在");
        }
        FileUtils.setHeaders(response, fileName);
        FileInputStream fileInputStream = new FileInputStream(file);
        //一次写入，大文件分开写会好点，参考minio的实现
        byte[] bytes = new byte[fileInputStream.available()];
        fileInputStream.read(bytes);
        response.getOutputStream().write(bytes);
        response.getOutputStream().flush();
        fileInputStream.close();
    }

    @Override
    public void delete(String fileName) {
        Assert.notNull(fileName, "文件名不能为空");
        File file = new File(FILE_ROOT, fileName);
        if (file.exists()) {
            file.delete();
        }
    }

}
